import { reactive } from 'vue'

function getDeptTreeList(data: DeptTree[]) {
  const deptTreeList = [] as DeptTree[]
  data.forEach((item) => {
    deptTreeList.push(item)
    if (item.children) {
      deptTreeList.push(...getDeptTreeList(item.children))
    }
  })
  return deptTreeList
}

export default reactive<DeptTreeStore>({
  usedList: [],
  deptTreeList: [],
  deptTree: [],
  setDeptTree(data: DeptTree[]) {
    this.deptTree = data
    this.deptTreeList = getDeptTreeList(data)
  },
  getDeptTreeNameById(id: number) {
    //先从缓存中去找
    if (this.usedList.length) {
      const usedDeptTreeList = this.usedList.filter((item) => Number(item.id) === Number(id))
      if (usedDeptTreeList.length) return usedDeptTreeList[0].label
    }
    //如果没找到，再从全部列表中去查找
    const deptTreeList = this.deptTreeList.filter((item) => Number(item.id) === Number(id))
    if (deptTreeList.length) {
      this.usedList.push(...deptTreeList)
      return deptTreeList[0].label
    } else {
      return ''
    }
  }
})
